/********************************** (C) COPYRIGHT  *******************************
 * File Name          : debug.c
 * Author             : WCH
 * Version            : V1.0.0
 * Date               : 2019/10/15
 * Description        : This file contains all the functions prototypes for UART
 *                      Printf , Delay functions.
 *********************************************************************************
 * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
 * Attention: This software (modified or not) and binary are used for 
 * microcontroller manufactured by Nanjing Qinheng Microelectronics.
 *******************************************************************************/
#include "debug.h"
#include <stdio.h>

 
#ifdef __cplusplus

extern "C" {

#endif

 

#define DEFAULT_HANDLE 0x100;

#include <rt_sys.h>

/*

 * These names are special strings which will be recognized by 

 * _sys_open and will cause it to return the standard I/O handles, instead

 * of opening a real file.

 */

const char __stdin_name[] ="STDIN";

const char __stdout_name[]="STDOUT";

const char __stderr_name[]="STDERR";

 

/*

 * Open a file. May return -1 if the file failed to open. We do not require

 * this function to do anything. Simply return a dummy handle.

 */

FILEHANDLE _sys_open(const char * name, int openmode)

{

    return DEFAULT_HANDLE;  

}

 

/*

 * Close a file. Should return 0 on success or a negative value on error.

 * Not required in this implementation. Always return success.

 */

int _sys_close(FILEHANDLE fh)

{

    return 0; //return success

}

 



 

/*

 * Read from a file. Can return:

 *  - zero if the read was completely successful

 *  - the number of bytes _not_ read, if the read was partially successful

 *  - the number of bytes not read, plus the top bit set (0x80000000), if

 *    the read was partially successful due to end of file

 *  - -1 if some error other than EOF occurred

 * This function receives a character from the UART, processes the character

 * if required (backspace) and then echo the character to the Terminal 

 * Emulator, printing the correct sequence after successive keystrokes.  

 */

int _sys_read(FILEHANDLE fh, unsigned char * buf,

              unsigned len, int mode)

{
		return 0;
}

 
/*

 * Write to a file. Returns 0 on success, negative on error, and the number

 * of characters _not_ written on partial success. This implementation sends

 * a buffer of size 'len' to the UART.

 */

int _sys_write(FILEHANDLE fh, const unsigned char * buf,

               unsigned len, int mode)

{

    int i;

    for(i=0;i <len;i++)  {

        fputc(buf[i],NULL);
    }

    return 0;   

}



/*

 * Writes a character to the output channel. This function is used

 * for last-resort error message output.

 */

void _ttywrch(int ch)

{

}

 

/*

 * Return non-zero if the argument file is connected to a terminal.

 */

int _sys_istty(FILEHANDLE fh)

{

    return 1; // no interactive device present

}

 

/*

 * Move the file position to a given offset from the file start.

 * Returns >=0 on success, <0 on failure. Seeking is not supported for the 

 * UART.

 */

int _sys_seek(FILEHANDLE fh, long pos)

{

    return -1; // error

}

 

/*

 * Flush any OS buffers associated with fh, ensuring that the file

 * is up to date on disk. Result is >=0 if OK, negative for an

 * error.

 */

int _sys_ensure(FILEHANDLE fh)

{

    return 0; // success

}

 

/*

 * Return the current length of a file, or <0 if an error occurred.

 * _sys_flen is allowed to reposition the file pointer (so Unix can

 * implement it with a single lseek, for example), since it is only

 * called when processing SEEK_END relative fseeks, and therefore a

 * call to _sys_flen is always followed by a call to _sys_seek.

 */

long _sys_flen(FILEHANDLE fh)

{

    return 0;

}

 

/*

 * Return the name for temporary file number sig in the buffer

 * name. Returns 0 on failure. maxlen is the maximum name length

 * allowed.

 */

int _sys_tmpnam(char * name, int sig, unsigned maxlen)

{

    return 0; // fail, not supported

}

 

/*

 * Terminate the program, passing a return code back to the user.

 * This function may not return.

 */

void _sys_exit(int returncode)

{

    while(1) {};

}

 

#ifdef __cplusplus

}

#endif


static u8  p_us=0;								   
static u16 p_ms=0;					

/*********************************************************************
 * @fn      Delay_Init
 *
 * @brief   Initializes Delay Funcation.
 *
 * @return  none
 */	
void Delay_Init(void)
{
	SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);	
	p_us=SystemCoreClock/8000000;			  
	p_ms=(u16)p_us*1000;					   
}								    

/*********************************************************************
 * @fn      Delay_Us
 *
 * @brief   Microsecond Delay Time.
 *
 * @param   n - Microsecond number.
 *
 * @return  None
 */
void Delay_Us(u32 n)
{		
	u32 i;	
	
	SysTick->LOAD=n*p_us; 						  		 
	SysTick->VAL=0x00;        					
	SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ;
	
	do
	{
		i=SysTick->CTRL;
	}while((i&0x01)&&!(i&(1<<16)));
	
	SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk;	
	SysTick->VAL =0X00;     	 
}

/*********************************************************************
 * @fn      Delay_Ms
 *
 * @brief   Millisecond Delay Time.
 *
 * @param   n - Millisecond number.
 *
 * @return  None
 */
void Delay_Ms(u16 n)
{	 		  	  
	u32 i;	
	
	SysTick->LOAD=(u32)n*p_ms;				
	SysTick->VAL =0x00;							
	SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ;
	
	do
	{
		i=SysTick->CTRL;
	}while((i&0x01)&&!(i&(1<<16)));	
	
	SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk;	
	SysTick->VAL =0X00;        	    
} 


/*********************************************************************
 * @fn      fputc
 *
 * @brief   Support Printf Function 
 *
 * @param   data - UART send Data.
 *          
 * @return  data - UART send Data.
 */
int fputc(int data, FILE *f)
{
#if (DEBUG == DEBUG_UART1)
  while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
	USART_SendData(USART1, (u8) data);
#elif (DEBUG == DEBUG_UART2)
  while (USART_GetFlagStatus(USART2, USART_FLAG_TC) == RESET);
  USART_SendData(USART2, (u8) data);	
#elif (DEBUG == DEBUG_UART3)
  while (USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET);	
  USART_SendData(USART3, (u8) data);	
#endif
	
  return data;
}

/*********************************************************************
 * @fn      USART_Printf_Init
 *
 * @brief   Initializes the USARTx peripheral.
 *
 * @param   baudrate - USART communication baud rate.
 *
 * @return  None
 */
void USART_Printf_Init(u32 baudrate)
{
  GPIO_InitTypeDef GPIO_InitStructure;
  USART_InitTypeDef USART_InitStructure;
	
#if (DEBUG == DEBUG_UART1)	
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE);	
  
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; 
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;	
  GPIO_Init(GPIOA, &GPIO_InitStructure);
	
#elif (DEBUG == DEBUG_UART2)
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);	
  
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; 
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;	
  GPIO_Init(GPIOA, &GPIO_InitStructure);
	
#elif (DEBUG == DEBUG_UART3)	
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);	
  
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; 
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;	
  GPIO_Init(GPIOB, &GPIO_InitStructure);
	
#endif	
   
  USART_InitStructure.USART_BaudRate = baudrate;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Tx;

#if (DEBUG == DEBUG_UART1)	
  USART_Init(USART1, &USART_InitStructure); 
  USART_Cmd(USART1, ENABLE);  
	
#elif (DEBUG == DEBUG_UART2)	
  USART_Init(USART2, &USART_InitStructure); 
  USART_Cmd(USART2, ENABLE);
	
#elif (DEBUG == DEBUG_UART3)
  USART_Init(USART3, &USART_InitStructure); 
  USART_Cmd(USART3, ENABLE);
	
#endif	
}


